<template>
	<view>
		<customHeader centerTitle="待付款订单" backThem="dark">
			<template v-slot:bg>
				<image class="head-bg" src="../../../static/image/version/headBg.png"></image>
			</template>
		</customHeader>
		<view class="all-page">
			<view class="page-pad">
				<view class="card-flor">
					<view>
						<view @click="checkAddress">
							<view>
								<tetx class="tips" v-if="!form.addressId">选择收货地址</tetx>
								<view v-else>
									<view>{{ addressInfo.username }}<text>{{ addressInfo.telephone }}</text></view>
									<view>{{addressInfo.address}}</view>
								</view>
							</view>
						</view>
						<image :src="require('@/userPackage/image/sgark.png')"></image>
					</view>
				</view>
				<view class="product-row">
					<view v-for="(it, ix) in productList" class="pro-all">
						<image mode="aspectFill" :src="it.goods_info.image"></image>
						<view>
							<view>{{ it.goods_info.name }}</view>
							<view>
								<view>x{{ it.number }}</view>
								<view>
									<text>¥</text>{{ it.totolPrice }}
								</view>
							</view>
							<view>{{it.goods_attr.name}}</view>
						</view>
					</view>
					<view class="outher-row">
						<view @click="openCound">
							<text>使用优惠券</text>
							<view hover-class="hover_clas">
								<text class="reds" v-if="couponList.length == 0">暂无优惠券</text>
								<text v-else>{{form.memberCouponId ? form.memberCouponName : '请选择'}}</text>
								<image :src="require('@/userPackage/image/sgark.png')"></image>
							</view>
						</view>
						<view>
							<text>配送费</text>
							<view>
								<text>{{ form.deliveryPrice == 0 ? '免配送费' : form.deliveryPrice }}</text>
							</view>
						</view>
						<view class="cloumn">
							<text>备注</text>
							<view>
								<textarea placeholder="请输入" v-model="form.remarks"></textarea>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="btn-group">
				<view>
					<view>
						<view>
							¥{{ form.totalPrice }}
						</view>
						<view>已优惠￥{{ form.couponPrice || 0 }}</view>
					</view>
					<view @click="showModal" hover-class="hover_class">去支付</view>
				</view>
			</view>
		</view>
		<u-picker
		keyName="name"
		confirmColor="#0B59E0"
		:show="coundPop" 
		@cancel="coundPop = false"
		@confirm="checkCoupond"
		:columns="couponList"></u-picker>
		<u-modal :show="show" @confirm="confirm" title="购买须知" :closeOnClickOverlay="true">
			<view class="slot-content">
				<mp-html :content="html" />
			</view>
		</u-modal>
	</view>
</template>

<script>
import { calc } from '@/utils/calc.js'
	import {
		defaultAddress,
		createOrder,
		orderSure,
		orderPay
	} from 'utils/api/order.js'
	import {
		advertGetInfo
	} from 'utils/api/home.js'
	import store from "@/store"
	export default {
		data() {
			return {
				coundPop: false,
				form: {
					addressId: '',
					memberCouponId: '', //
					memberCouponName: '', //
					cartIds: [],
					productPrice: '',
					couponPrice: '', //
					deliveryDistance: '',
					deliveryPrice: '',
					totalPrice: 0,
					remarks: '',
				},
				productList: [],
				couponList: [],
				addressInfo: {},
				ruleToast: {
					addressId: '请选择收货地址',
				},
				show:false,
				html: ''
			}
		},
		onLoad(data) {
			const carts = JSON.parse(uni.getStorageSync('cart'))
			this.form.cartIds = carts.map((it) => it.id)
			this.getDefaultAddress()
			this.getInfo()
		},
		watch: {
			'form.addressId': {
				handler(val) {
					this.getSure()
				},
				deep: true,
			}
		},
		onShow() {
			uni.$on('addressData',(data) => {
				this.form.addressId = data.id
				this.addressInfo = data
			})
		},
		methods: {
			// 打开优惠券
			openCound() {
				if(this.couponList.length) {
					this.coundPop = true
				}
			},
			// 选择优惠
			checkCoupond(data) {
				const {id, name, type, full, reduce, discount} = data.value[0]
				const {totalPrice} = this.form
				if (type == 1) {
					if(Number(this.form.totalPrice) < Number(full)) {
						return uni.showToast({
							title: '当前金额不满足满减'
						})
					}
					this.form.couponPrice = reduce
				} else {
					// let counPrice = (totalPrice * (discount / 10)).toFixed(2)
					let counPrice = calc.cheng(totalPrice, calc.chu(discount, 10))
					// this.form.couponPrice = (totalPrice - counPrice).toFixed(2)
					this.form.couponPrice = calc.sub(totalPrice, counPrice)
				}
				this.form.memberCouponId = id
				this.form.memberCouponName = name
				// this.form.totalPrice = totalPrice - (this.form.couponPrice || 0)
				this.form.totalPrice = calc.sub(totalPrice, (this.form.couponPrice || 0))
				this.coundPop = false
			},
			// 获取价格
			getSure() {
				orderSure({
					member_address_id: this.form.addressId,
					cartIds: this.form.cartIds
				}).then((res) => {
					const {product_list, total_price, product_price, delivery_price, delivery_distance, coupon_list} = res.data
					this.productList = (product_list || []).map(it => {
						return {
							...it,
							totolPrice: calc.cheng(it.price, it.number)
						}
					})
					this.form.totalPrice = total_price || 0
					this.form.productPrice = product_price
					this.form.deliveryPrice = delivery_price
					this.form.deliveryDistance = delivery_distance
					this.setCoupond(coupon_list)
				})
			},
			// 重置优惠券内容
			setCoupond(data) {
				let list = data
				if(!list.length) return
				list.forEach((it) => {
					if(it.type == 1) {
						it.name = `${it.name}(满${it.full}减${it.reduce})`
					} else {
						it.name = `${it.name}(${it.discount}折)`
					}
				})
				this.couponList = [list]
			},
			
			// 获取购买须知内容
			getInfo() {
				uni.showLoading({
					title: '加载中'
				})
				advertGetInfo({id: 1}).then((res) => {
					this.html = res.data.content	
				}).finally(() => {
					uni.hideLoading()
				})
			},
			showModal() {
				if(!this.form.addressId) {
					return uni.showToast({
						title: '请选择收货地址',
						icon: 'none'
					})
				}
				this.show = true
			},
			confirm() {
				this.show = false
			  this.payOrder()
			},
			payOrder(key) {
				uni.showLoading({
					title: '下单中',
					mask: true
				})
				let that = this
				createOrder(this.form).then((res) => {
					uni.hideLoading()
					uni.showToast({ title: '下单成功', icon: 'none'})
					this.goPay(res)
				})
			},
			// 支付
			goPay(res) {
				uni.showLoading({
					title: '支付中'
				})
				orderPay({
					...this.form,
					id: res.data
				}).then((res) => {
					uni.hideLoading()
					let {timeStamp,nonceStr,signType,paySign} = res.data;
					uni.requestPayment({
						provider: 'wxpay',    //支付类型-固定值
						timeStamp: timeStamp, // 时间戳（单位：秒）
						nonceStr: nonceStr, // 随机字符串
						package: res.data.package, // 固定值
						signType:signType, //固定值
						paySign: paySign, //签名
						success: function (res) {
							uni.showToast({ title: '支付成功', icon: "none" });
							setTimeout(() => {
								uni.navigateBack()
							}, 500)
						},
						fail: function (err) {
							uni.showToast({ title: '支付失败', icon: "none" });
							setTimeout(() => {
								uni.navigateBack()
							}, 500)
						}
					});
				})
			},
			// 获取默认地址
			getDefaultAddress() {
				defaultAddress().then((res) => {
					if(res.data && res.data.length !==0) {
						this.form.addressId = res.data.id
						this.addressInfo = res.data
					} else {
						this.getSure()
					}
				})
			},
			// 选择地址
			checkAddress() {
				uni.navigateTo({
					url: '/userPackage/pages/addressMan/index?type=check'
				})
			}
		}
	}
</script>

<style scoped lang="scss">
@import './index.scss';
</style>